<template>
  <div class="image-container">
    <div class="label">
      {{ label }}
      <span class="tips">
        {{ tips }}
        <template v-if="max">
          （最多只能上传{{ max - imageList.length }}张图片）
        </template>
      </span>
    </div>

    <div class="content">
      <flexbox class="images">
        <div v-for="(item, index) in imageList" :key="index" class="img-box">
          <img v-src="item.url" :key="item.url" class="img">
          <div class="img-model">
            <i class="el-icon-zoom-in set-img-zoom" @click.stop="previewImage(index)"/>
            <i class="el-icon-delete set-img-delete" @click.stop="deleteImg(index)"/>
          </div>
        </div>

        <div v-if="imageList.length < max" class="img-upload-box img-item" @click="upLoadImg">
          <input ref="detailImgInput"
                 accept="image/*"
                 type="file"
                 multiple
                 class="file-input"
                 @change="upLoad">
          <el-button link icon="el-icon-plus" class="cross"/>
        </div>
      </flexbox>
    </div>
  </div>
</template>

<script setup>

import {getCurrentInstance, nextTick, ref, watch} from "vue";
import {adminFileDeleteByIdAPI, adminFileUploadAPI} from "@/api/admin/file.js";
import {guid, objDeepCopy} from "utils";
import {ElMessage, ElMessageBox} from "element-plus";



const cxt = getCurrentInstance()
const bus = cxt.appContext.config.globalProperties.$bus
const $wkPreviewFile = cxt.appContext.config.globalProperties.$wkPreviewFile
const $wkUploadFile = cxt.appContext.config.globalProperties.$wkUploadFile


defineOptions({
  name: 'WkImageForm',
})

const props = defineProps({
  value: { // 绑定的 batchId
    type: String,
    default: ''
  },
  max: { // 最大上传图片数量，值为0时不限制
    type: Number,
    default: 9
  },
  label: { // 图片标题
    type: String,
    default: '图片信息'
  },
  tips: { // 图片提示
    type: String,
    default: ''
  },
  defaultValue: { // 默认图片数组
    type: Array,
    default: () => []
  },
  field: { // 附加辅助参数
    type: Object,
    default: () => {
    }
  },
  initBatchId: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits([])


const loading = ref(false)
const imageList = ref([])
const batchId = ref(null)
const oldBatchId = ref(null)


watch(() => props.defaultValue, (val) => {
      if (val.length > 0) {
        imageList.value = objDeepCopy(val || [])
        nextTick(() => {
          batchId.value = props.defaultValue[0].batchId
          emits('input', props.defaultValue[0].batchId)
          updateVal()
        })
      }
    },
    {
      deep: true,
      immediate: true
    })

watch(() => props.value, (val) => {
      batchId.value = val || null
    },
    {
      immediate: true
    })

function previewImage(index)
{
  $wkPreviewFile.preview({
    index: index,
    data: imageList.value
  })
}

function deleteImg(index) {
  const params = {}
  params.id = imageList.value[index].fileId

  ElMessageBox.confirm('此操作将永久删除该图片, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    adminFileDeleteByIdAPI(params.id).then(res => {
      ElMessage.success({message:'删除成功'})
      imageList.value.splice(index, 1)
      updateVal()
      loading.value = false
    }).catch(() => {
      loading.value = false
    })
  }).catch(() => {
    ElMessage.info({message: '已取消删除'})
  })
}

function upLoadImg() {
  cxt.refs.detailImgInput.click()
}

function upLoad(event) {
  let files = Array.from(event.target.files)
  if (props.max && files.length + imageList.value.length > props.max) {
    files = files.slice(0, props.max - props.primaryList.length)
    ElMessage.error({message:`最多只能上传${props.max}张图片`})
  }

  if (files.length === 0) return
  if (!batchId.value && files.length > 1) {
    batchId.value = guid()
  }
  for (let index = 0; index < files.length; index++) {
    const params = {}
    if (batchId.value) {
      params.batchId = batchId.value
    }
    // if (this.initBatchId && !this.oldBatchId) {
    //   delete params.batchId
    // }
    $wkUploadFile.upload({
      request: adminFileUploadAPI,
      file: files[index],
      params: params
    }).then(data => {
      const {res} = data
      batchId.value = res.data.data.batchId
      oldBatchId.value = batchId.value

      res.data.url = `/adminFile/down/${res.data.fileId}`
      imageList.value.push(res.data)
      loading.value = false
      updateVal()
    }).catch(() => {
    })
  }
}

function updateVal() {
  console.log('change-----: ', props.field, batchId.value, imageList.value)
  if (imageList.value.length === 0) {
    emits('change', props.field, null, [])
    emits('input', '')
  } else {
    emits('change', props.field, batchId.value, imageList.value)
    emits('input', batchId.value)
  }
}


</script>


<style scoped lang="scss">
.image-container {
  margin-left: 15px;

  .label {
    font-size: 13px;
    margin-top: 20px;

    .tips {
      color: #C1C1C1;
    }
  }

  .content {
    .images {
      overflow-x: auto;
      margin: 10px 0;

      .img-box {
        position: relative;
        margin-right: 20px;
        flex-shrink: 0;
        cursor: pointer;

        &:hover {
          .img-model {
            visibility: visible;
          }
        }

        .img {
          width: 100px;
          height: 80px;
          border-radius: $xr-border-radius-base;
        }

        .img-model {
          position: absolute;
          z-index: 10;
          line-height: 86px;
          background-color: #2d3037;
          opacity: 0.8;
          border-radius: 6px;
          visibility: hidden;
          top: 0;
          left: 0;
          bottom: 0;
          right: 0;

          .set-img-zoom {
            font-size: 20px;
            color: white;
            cursor: pointer;
            padding-left: 15px;
          }

          .set-img-delete {
            font-size: 20px;
            color: white;
            padding-left: calc(50% - 35px);
            cursor: pointer;
          }
        }
      }

      .img-upload-box {
        flex-shrink: 0;
        width: 100px;
        height: 80px;
        display: flex;
        cursor: pointer;
        border-radius: 6px;
        position: relative;
        text-align: center;
        border: 1px #c0ccda dashed;
        margin-bottom: 5px;

        .file-input {
          width: 0;
          height: 0;
          visibility: hidden;
        }

        .cross {
          color: #606266;
          font-size: 20px;
          margin-left: calc(50% - 10px);
        }
      }
    }
  }
}

:deep(.el-icon-zoom-in) {
  margin-right: 10px;
}
</style>
